//
//  HMWeiboTabBarController.swift
//  01-启动图片的搭建
//
//  Created by 白利兵 on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class HMWeiboTabBarController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置背景色
        self.view.backgroundColor = UIColor.whiteColor()
        // 创建子控制器
        makeChildrenController()
        // 创建添加按钮
        setComposeBtn()
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        // 把按钮带到tabbar最顶部
        tabBar.bringSubviewToFront(composeBtn)
    }
    // 创建添加按钮
    private lazy var composeBtn: UIButton = {
        // 创建添加按钮
        let button = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
        button.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
        }()
}

extension HMWeiboTabBarController {
    // 添加按钮
    private func setComposeBtn() {
        // 1. 添撰写按钮
        tabBar.addSubview(composeBtn)
        // 2. 调整按钮
        let count = childViewControllers.count
        // 3.让按钮宽一点点，能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        composeBtn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
    }
    // 监听按钮的点击事件
    @objc private func composeBtnClick() {
       print("撰写文章")
        // 创建撰写控制器
        let composeVC = HMComposeController()
        //composeVC.view.backgroundColor = UIColor.orangeColor()
        // 创建导航控制器
        let navgVC = UINavigationController(rootViewController: composeVC)
        // 跳转到导航控制器
        self.presentViewController(navgVC, animated: true, completion: nil)
    }
    // 创建子控制器
    private func makeChildrenController() {
        
        let homeVC = HMHomeTableViewController()
        let messageVC = HMMessageTableViewController()
        let discoverVC = HMDiscoverViewController()
        let profileVC = HMProfileTableViewController()
        
        // 把控制器添加到tabBarController中
        addChildViewControllers(homeVC, title: "主页", imageName: "tabbar_home")
        addChildViewControllers(messageVC, title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewControllers(discoverVC, title: "发现", imageName: "tabbar_discover")
        addChildViewControllers(profileVC, title: "我", imageName: "tabbar_profile")
        
    }
    
    private func addChildViewControllers(vc: UIViewController, title: String, imageName: String) {
        // 创建一个NavigationController
        let navgController = UINavigationController(rootViewController: vc)
        // 设置标题
        vc.title = title;
        vc.tabBarItem.image = UIImage(named: imageName)
        // 把控制器添加到tabbarController中
        addChildViewController(navgController)
    }
}





